package com.lingnan.blog.service;

import com.lingnan.blog.entity.User;
import com.lingnan.blog.mapper.UserMapper;
import com.lingnan.blog.utils.DateUtil;
import com.lingnan.blog.utils.IpUtil;
import com.lingnan.blog.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.UnknownHostException;
import java.util.Date;

/**
 * @author HeGuanChao
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(Integer id){
        return userMapper.selectById(id);
    }

    public int saveUser(User user) throws UnknownHostException {
        //用户不存在
        //密码md5加盐加密
        Md5Util.encryptPassword(user);
        //设置ip
        user.setIp(IpUtil.getHostAddress());
        //注册时间
        user.setRetime(DateUtil.format(new Date()));
        //角色
        user.setRole("用户");
        return userMapper.insert(user);
    }

    public User finByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    public int updateUser(User user) {
        return userMapper.update(user);
    }

    public User findArticlesById(Integer id) {
        return userMapper.selectArticlesById(id);
    }

    public User findByUserRole(String user_role) {
        return userMapper.selectByUserRole(user_role);
    }
}
